import 'package:flutter/material.dart';
import '../../services/message_manger.dart';
import '../../models/message_model.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../login/controller/webview.dart';
import '../../manger/user_manger.dart';
import '../../login/controller/login_view.dart';
import '../../manger/global_config.dart';
import 'dart:io'; // 引入 dart:io 库
import '../controller/msg_list_page.dart';
import '../../manger/network_utils.dart';
import '../../components/toast_utils.dart';
import '../../services/global_state.dart';
import 'package:provider/provider.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/umevent_utils.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  _MessagePageState createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> with AutomaticKeepAliveClientMixin{
  List<MsgOrderModel> msgList = [];
  bool isNeedClear = false;
  @override
  bool get wantKeepAlive => true;
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    final manager = MeassageInfoManager();
    final success = await manager.loadInfoData();
    if (success.success) {
      int countTotal = 0;
      if (success.msgListModel != null) {
        for (var model in success.msgListModel!) {
          countTotal += model.count;
        }
      }
      Provider.of<GlobalState>(context, listen: false).updateMessageCount(countTotal);
      setState(() {
        // 如果 msgListModel 为 null，使用空列表
        msgList = (success.msgListModel ?? []).where((item) => item != null).toList();
        isNeedClear = msgList.any((msg) => msg.count > 0);
      });

    } 

    if (!UserInfos.shared.token.isNotEmpty) {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const LoginView()),
      );
    }
  }

  void clearMessages(int type) async{
    if (!isNeedClear) {
        ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.noUnreadMessages);
        return;
      }

     try {
      final response = await NetworkUtils.post(
        RequestCmd.messagesread,
        body: {"type": type},
      );

      if (response['code'] == 200) {
        _loadData();
        if (type == 3) {
          ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.allMessagesIsRead);
        }
      } else {
        ToastUtils.showCenterToast(context, response['msg']);
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              localizations.messageCenter,
              style: TextStyle(color: Color(0xFF000000),fontSize: 16),
            ),
            SizedBox(width: 3),
            GestureDetector(
              onTap: () => clearMessages(3),
              child: Image.asset("assets/images/msgclear.png", width: 20, height: 20),
            ),
          ],
        ),
      ),
      body: ListView.builder(
        itemCount: msgList.length + 1,  // msgList + 1 是为了容纳 Container 作为第一个元素
        itemBuilder: (context, index) {
          // 如果是第一个 item，就返回 Container 作为第一个 cell
          if (index == 0) {
            return Container(
              height: 110,  // 设置固定高度
              padding: const EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
              child: GestureDetector(
                onTap: () {
                  UmengEvent.trackEvent("info_kefu_click","消息菜单中，点击联系客服","");
                  // TODO: 跳转到客服聊天
                  QYSDK.showQYSession();
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white, // 背景色
                    borderRadius: BorderRadius.circular(15), // 圆角
                  ),
                  padding: const EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 0),
                  child: Row(
                    children: [
                      Image.asset("assets/images/message.png", width: 50, height: 50),
                      const SizedBox(width: 16),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            localizations.onlineCustomer,
                            style: const TextStyle(color: Color(0xFF000000), fontSize: 17),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            localizations.helloDearHowCanIHelpYou,
                            style: const TextStyle(color: Color(0xFF999999), fontSize: 13),
                          ),
                        ],
                      ),
                      const Spacer(),
                      Text(
                        localizations.twoMinutesAgo,
                        style: const TextStyle(color: Color(0xFF999999), fontSize: 13),
                      ),
                    ],
                  ),
                )

              ),
            );
          }

          // 对于后续的消息项，返回 MsgViewCell
          return MsgViewCell(
          msgList[index - 1],
          clearMessages: (type) => clearMessages(type),
          poppage: () {
            _loadData();
          },
        ); // 注意索引需要减1，因为第一个 item 是 Container
        },
      ),
    );
  }
}

class MsgViewCell extends StatelessWidget {
  final MsgOrderModel model;
  final Function(int) clearMessages;
  final Function() poppage;

  const MsgViewCell(this.model, {Key? key, required this.clearMessages, required this.poppage}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    // 使用 SizedBox 固定高度为 116
    return SizedBox(
      height: 110,
      child: Container(
  margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
  decoration: BoxDecoration(
    color: Colors.white, // 背景色
    borderRadius: BorderRadius.circular(15), // 圆角
  ),
  child: ListTile(
    contentPadding: const EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
    leading: SizedBox(
      width: 50,
      height: 50,
      child: Image.asset(
        model.stype == 0 ? 'assets/images/message1.png' : 'assets/images/message2.png',
        fit: BoxFit.contain,
      ),
    ),
    title: Row(
      children: [
        Text(
          model.stype == 0 ? localizations.orderStatus : localizations.youhuicuxiao,
          style: const TextStyle(color: Color(0xFF000000), fontSize: 17),
        ),
        if (model.count > 0)
          Container(
            width: 8,
            height: 8,
            margin: const EdgeInsets.only(left: 4),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(4),
            ),
          )
      ],
    ),
    subtitle: Text(
      model.stype == 0 ? localizations.dingdanyichang : localizations.miaosha,
      style: const TextStyle(color: Color(0xFF999999), fontSize: 13),
    ),
    trailing: Text(
      model.time,
      style: const TextStyle(color: Color(0xFF999999), fontSize: 13),
    ),
    onTap: () {
      if (model.stype == 0) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const MsgListView()),
        ).then((value) {
          poppage();
        });
      } else {
        final String platformType = Platform.isIOS ? 'iOS' : 'Android';
        String arcodeUrl =
            "${UrlConfig.yhcxURL(context)}terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}";
        if (UserInfos.shared.userModel?.countryEn != null &&
            UserInfos.shared.userModel!.countryEn.isNotEmpty) {
          if (UserInfos.shared.userModel!.countryEn == "CN") {
            arcodeUrl = "$arcodeUrl&access=86";
          }
        }
        UmengEvent.trackEvent(
            "info_activity_click", "消息菜单中，点击优惠促销模块", "");

        clearMessages(1);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => WebViewPage(
              title: AppLocalizations.of(context)!.youhuicuxiao,
              url: arcodeUrl,
            ),
          ),
        );
      }
    },
  ),
)

    );
  }
}
